<?php
namespace Admin\Controller;
use Think\Controller;
class UserController extends CommonController {
	//添加用户
	public function addUser(){
		$this->role = M('role')->select();
		$this->display();
	}

	//添加用户处理表单
	public function addUserHandle(){
		if(!IS_POST) $this->error("提交方式错误");
		$data['username'] = I('username');
		$data['password'] = I('password','','md5');
		$data['email'] = I('email');
		$rules = array(  
			array('username','','帐号名称已经存在！',0,'unique',1), // 在新增的时候验证name字段是否唯一     
			array('email','email','邮箱格式不正确'), //默认情况下用正则进行验证
		    array('email','require','邮箱不能为空'), //默认情况下用正则进行验证
		    array('email','','邮箱已经存在！',0,'unique',1), // 在新增的时候验证name字段是否唯一 
		);
		 $user = M('user');
		 if (!$user->validate($rules)->create()){
		 	$this->error("注册失败:".$user->getError());  
		 } else{
		 	$uid = M('user')->add($data); //获取添加后的uid
		 	$role['role_id'] = I('role_id');
		 	$role['user_id'] = $uid;
		 //	p($role);die;
		 	if(M('role_user')->add($role)){
		 		$this->success("用户注册成功");
		 	}else{
		 		$this->error("用户注册失败");
		 	}
		 	
		 }
	}	 
	//删除用户
	public function delUser(){
		$this->display();
	}
	//删除用户处理表单
	public function delUserHandle(){
		if(!IS_POST) $this->error("提交方式错误");
		$db = M('user');
		$username = I('username');
		$result = $db->where(array('username'=>$username,))->delete();
		if(!$result)
			$this->error("删除失败,用户不存在");
		$this->success("删除成功");

	}	
	//锁定用户
	public function lockUser(){
		$this->display();
	}

	//锁定用户处理表单
	public function lockUserHandle(){
		if(!IS_POST) $this->error("提交方式错误");
		$db = M('user');
		$username= I('username');
		$result = $db->where(array("username"=>$username))->setField('status',"1");
		if(!$result)
			$this->error("用户锁定失败");
		$this->success("用户锁定成功");
	}
	//解锁用户
	public function unlockUser(){
		$this->display();
	}

	//解锁用户处理表单
	public function unlockUserHandle(){
		if(!IS_POST) $this->error("提交方式错误");
		$db = M('user');
		$username= I('username');
		$result = $db->where(array("username"=>$username))->setField('status',"0");
		if(!$result)
			$this->error("用户解锁失败");
		$this->success("用户解锁成功");
	}		
	//查看用户
	public function viewUser(){
		$db = D('user');
	//	p($db);die;
		$count = $db->count();
		//数据分页
		$Page = new \Think\Page($count,10);	
		$Page ->setConfig('theme','<div id="pageinfo">%HEADER%，%NOW_PAGE%/%TOTAL_PAGE%页 </div> <div id="page">%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% </div>');
		$show = $Page->show();// 分页显示输出
		$list = $db->limit($Page->firstRow.','.$Page->listRows)->relation(true)->field('password',true)->select();
		$this->assign('page',$show);
		$this->assign('result',$list);
		$this->assign('count',$count);
		$this->display();
	}
}